package io.renren.modules.app.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.form.FinanceWishdrawalsAppForm;
import io.renren.modules.finance.entity.FinanceMoneyRecord;
import io.renren.modules.finance.entity.FinanceWithdrawalsApp;
import io.renren.modules.finance.entity.FinanceWithdrawalsSetting;
import io.renren.modules.finance.entity.UserMoneyTotal;
import io.renren.modules.finance.service.FinanceMoneyRecordService;
import io.renren.modules.finance.service.FinanceWithdrawalsAppService;
import io.renren.modules.finance.service.FinanceWithdrawalsSettingService;
import io.renren.modules.finance.service.UserMoneyTotalService;
import io.renren.modules.user.entity.UserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: agent-server
 * @description: 财务- 收益账户
 * @author: 郭亚坤
 * @create: 2019-03-13 14:07
 **/
@RestController
@RequestMapping("/app/fin")
public class FinIncomingController {

    @Autowired
    private FinanceWithdrawalsAppService financeWithdrawalsAppService;
    @Autowired
    private FinanceWithdrawalsSettingService financeWithdrawalsSettingService;
    @Autowired
    private UserMoneyTotalService agentMoneyTotalService;

    @Autowired
    private FinanceMoneyRecordService financeMoneyRecordService;

    /**
     * 代理申请提现
     *
     * @param financeWishdrawalsAppForm
     * @return
     */
    @PostMapping("withdraw")
    @Login
    public R withdraw(@LoginUser UserEntity user, @RequestBody FinanceWishdrawalsAppForm financeWishdrawalsAppForm) {
        FinanceWithdrawalsApp financeWithdrawalsAppEntity = new FinanceWithdrawalsApp();
        financeWithdrawalsAppEntity.setAmount(financeWishdrawalsAppForm.getAmount());

        financeWithdrawalsAppEntity.setUserId(user.getUserId());

        if (StringUtils.isBlank(financeWishdrawalsAppForm.getAccountName())) {
            return R.error("请输入提现账户认证姓名");
        }
        /**
         * 目前仅仅支持微信提现，直接把代理的账户信息设置成提现信息
         */
        financeWithdrawalsAppEntity.setAccountName(financeWishdrawalsAppForm.getAccountName());
        financeWithdrawalsAppEntity.setMethod(FinanceWithdrawalsApp.METHOD_WECHAT);
        financeWithdrawalsAppEntity.setAccountNo(financeWishdrawalsAppForm.getAccountNo());

        if (StringUtil.isNull(financeWishdrawalsAppForm.getAmount())) {
            return R.error("提现金额不能为空");
        }
//        1 商家回传凭证
//        2 每月提现次数
//        3 最低提现金额
//        4 是否开启手续费
//        5 手续费设置
//        6 提现审核等待
//        7 日提现金额上限
//        8 每笔提现金额上限
//        9 支付宝提现是否可用
//        10 微信提现是否可用

        List<FinanceWithdrawalsSetting> financeWithdrawalsSettingList = financeWithdrawalsSettingService.list();//读取到提现设置
        Map<String, Integer> settingMap = new HashMap<>();
        for (FinanceWithdrawalsSetting financeWithdrawalsSetting : financeWithdrawalsSettingList) {
            settingMap.put(financeWithdrawalsSetting.getTypeCode().toString(), financeWithdrawalsSetting.getItemValue());
        }
        //        2 每月提现次数
        int monthCount = financeWithdrawalsAppService.count(new QueryWrapper<FinanceWithdrawalsApp>()
                .eq("user_id", financeWithdrawalsAppEntity.getUserId())
                .gt("create_time", DateUtil.date())
                .lt("create_time", DateUtil.date())
        );
        if (monthCount > settingMap.get("2")) {
            return R.error("每月提现次数上限" + settingMap.get("2") + "次");
        }
        // 3 最低提现金额
        if (financeWithdrawalsAppEntity.getAmount().doubleValue() < settingMap.get("3")) {
            return R.error("单次提现金额最低" + settingMap.get("3") + "元");
        }
        // 6 提现审核等待
        if (1 == settingMap.get("6").intValue()) {
            if (financeWithdrawalsAppService.count(new QueryWrapper<FinanceWithdrawalsApp>()
                    .eq("status", FinanceWithdrawalsApp.STATUS_AUDIT)
                    .eq("user_id", financeWithdrawalsAppEntity.getUserId())
            ) > 0) {
                return R.error("您存在未处理的提现申请，请等待处理完成后再进行提现申请");
            }
        }
        // 8 每笔提现金额上限
        if (financeWithdrawalsAppEntity.getAmount().doubleValue() > settingMap.get("8")) {
            return R.error("单次提现金额上限" + settingMap.get("8") + "元");
        }
        // 检查用户可用提现余额
        UserMoneyTotal agentMoneyTotal = agentMoneyTotalService.getByUserId(financeWithdrawalsAppEntity.getUserId());
        if (agentMoneyTotal.getBalanceIncome().doubleValue() < financeWithdrawalsAppEntity.getAmount().doubleValue()) {
            return R.error("可提现账户余额不足");
        }
        boolean result = financeWithdrawalsAppService.apply(financeWithdrawalsAppEntity, agentMoneyTotal);
        return R.ok();
    }

//    /**
//     * 取消申请提现
//     *
//     * @param
//     * @param id
//     * @return
//     */
//    @PostMapping("cancel")
//    @Login(value = Login.LOGIN)
//    public RstModel withdrawCancel(HttpServletRequest request, Integer id) {
//        if (id == null) {
//            return RstModel.error("请选择要取消的申请记录");
//        }
//        FinanceWithdrawalsApp financeRechargeAccountEntity = financeWithdrawalsAppService.getById(id);
//        if (!financeRechargeAccountEntity.getAgentId().equals(PortalUtil.getCurrentAgent(request).getId())) {
//            return RstModel.error("非法操作");
//        }
//        if (financeRechargeAccountEntity.getStatus() != 1) {
//            return RstModel.error("取消已处理或取消，不能取消取现");
//        }
//        boolean result = financeWithdrawalsAppService.close(financeRechargeAccountEntity);
//        return RstModel.result(result);
//    }

    /**
     * 代理商余额的基本信息
     */
    @GetMapping("info")
    @Login
    public R info(@RequestAttribute("userId") Long userId) {
        UserMoneyTotal agentMoneyTotalEntity = agentMoneyTotalService.getByUserId(userId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("balanceIncome", agentMoneyTotalEntity.getBalanceIncome());// 可提现
        resultMap.put("withdrawLockMoney", agentMoneyTotalEntity.getWithdrawLockMoney().toString());// 提现中
        resultMap.put("totalIncome", agentMoneyTotalEntity.getTotalIncome().toString());// 提现中
        resultMap.put("withdrawTotal", agentMoneyTotalEntity.getWithdrawTotal().toString());// 提现中
        resultMap.put("balanceCoin", agentMoneyTotalEntity.getBalanceCoin());// 提现中
        resultMap.put("totalCoin", agentMoneyTotalEntity.getTotalCoin());// 提现中
        return R.ok(resultMap);
    }

    /**
     * 代理商余额的基本信息
     */
    @GetMapping("recordList")
    @Login
    public R info(@RequestAttribute("userId") Long userId,@RequestParam Map<String, Object> params) {
        params.put("userId",userId);
        PageUtils pageUtils = financeMoneyRecordService.queryAppPage(params);
        return R.ok().put(pageUtils);
    }
}
